package com.wf.smartcomm.server.interceptor;

import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.wf.smartcomm.server.response.ResponseCode;

public class PermissionInterceptor implements Interceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected final Logger logger = Logger.getLogger(PermissionInterceptor.class);
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init() {
		// TODO Auto-generated method stub

	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = null;
		try {
			invocation.invoke();
		} catch (Exception e) {
			out = response.getWriter();
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("code", ResponseCode.SERVER_EXCEPTION);
			StringBuilder trace = new StringBuilder();
			trace.append(e.toString()).append(System.getProperty("line.separator"));
			for (StackTraceElement element : e.getStackTrace()) {
				trace.append(element.toString()).append(System.getProperty("line.separator"));
			}
			map.put("data",trace.toString());
			out.print(new Gson().toJson(map));
			logger.warn((new StringBuilder("PermissionInterceptor:")).append(trace.toString()).toString());
		}finally{
			if (out != null) {
				out.close();
			}
		}
		return null;
	}

}
